package net.wicp.tams.common.redis.builder;

import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.commons.lang3.Validate;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import lombok.Builder;
import lombok.Builder.Default;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.common.Conf;
import net.wicp.tams.common.apiext.StringUtil;
import net.wicp.tams.common.redis.pool.JedisSentinelPoolTams;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisSentinelPool;
import redis.clients.jedis.Protocol;

@Builder
@Slf4j
@Getter
public class RedisSentinelBuilderTams {
	private GenericObjectPoolConfig<Jedis> poolConfig;
	private static final Lock LOCK = new ReentrantLock();
	@Default
	private int timeout = Protocol.DEFAULT_TIMEOUT;// 创建池的最大时间
	@Default
	private final JedisSentinelPoolTams jedisSentinelPoolTams = new JedisSentinelPoolTams();
	private String masterName;
	private Set<String> sentinels;

	private void init() {
		Validate.notNull(poolConfig, "需要配置信息");
		poolConfig.setJmxEnabled(true);
		poolConfig.setJmxNamePrefix("jedis-pool");
		if (jedisSentinelPoolTams.isInit()) {
			while (true) {
				try {
					LOCK.tryLock(100, TimeUnit.MILLISECONDS);
					if (jedisSentinelPoolTams.isInit()) {
						JedisSentinelPool jedisSentinelPool = new JedisSentinelPool(masterName, sentinels, poolConfig,
								timeout, timeout,
								StringUtil.hasNull(Conf.get("common.redis.redisserver.password"), null),
								Conf.getInt("common.redis.redisserver.defaultDb"),
								Conf.get("common.redis.redisserver.clientName"));
						jedisSentinelPoolTams.setJedisSentinelPool(jedisSentinelPool);
						LOCK.unlock();
						break;
					}
				} catch (InterruptedException e) {
					log.error("error in build().", e);
				}
			}
		}
		log.info("---------------the pool inited---------------");
	}

	public static class InternalBuilder extends RedisSentinelBuilderTamsBuilder {
		InternalBuilder() {
			super();
		}

		@Override
		public RedisSentinelBuilderTams build() {
			RedisSentinelBuilderTams model = super.build();
			model.init();
			return model;
		}
	}

	public static RedisSentinelBuilderTamsBuilder builder() {
		return new InternalBuilder();
	}
}
